package online.zhangwenzhe.common.security.Impl;

import com.sun.org.apache.xml.internal.security.utils.Base64;
import online.zhangwenzhe.common.CustomProperties;
import online.zhangwenzhe.common.security.TokenVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 说明：
 *
 * @author 张文哲
 * @version 1.0.0
 * @since 2018/7/3 16:25
 */

@Component
public class TokenVerifierRemoteImpl implements TokenVerifier {
    RestTemplate restTemplate;

    private CustomProperties customProperties;

    String checkTokenEndpoint = "http://localhost:8080/oauth/check_token";
    String client_id = "app";
    String client_secret = "secret";

    @Autowired
    public TokenVerifierRemoteImpl(CustomProperties customProperties) {
        this.checkTokenEndpoint = customProperties.getOauth2().getTokenEndpoint();
        this.client_id = customProperties.getOauth2().getClientId();
        this.client_secret = customProperties.getOauth2().getClientSecret();

        this.restTemplate = new RestTemplate();
    }

    @Override
    public String verify(String token) {
        String basicAuthHeader = generateBasicAuthHeaderString(client_id, client_secret);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Authorization", basicAuthHeader);
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);

        String username = null;

        try {
            ResponseEntity<Map> response = restTemplate.exchange(checkTokenEndpoint + "?token=" + token, HttpMethod.GET, requestEntity, Map.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                Object value = response.getBody().get("user_name");
                if (value != null) {
                    username = value.toString();
                }
            }
        } catch (Exception e) {
            return null;
        }

        return username;
    }

    // Authorization : Basic XXXXXXXXXX
    private String generateBasicAuthHeaderString(String client_id, String client_secret) {
        try {
            String base = "";
            if (client_secret == null
                    || client_secret.equals("")) {
                base = encodeURIComponent(client_id);
            } else {
                base = encodeURIComponent(client_id) + ":"
                        + encodeURIComponent(client_secret);
            }

            return "Basic " + Base64.encode(base.getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    // URL Encoding Utility
    private String encodeURIComponent(String s) {
        String result;

        try {
            result = URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20")
                    .replaceAll("\\%21", "!").replaceAll("\\%27", "'")
                    .replaceAll("\\%28", "(").replaceAll("\\%29", ")")
                    .replaceAll("\\%7E", "~");
        } catch (UnsupportedEncodingException e) {
            result = s;
        }

        return result;
    }
}
